<template>
  <div class="p-6 space-y-6">
    <div class="text-center">
      <h2 class="text-xl font-bold text-gray-900 mb-2">麦克风权限测试</h2>
      <p class="text-gray-600">测试麦克风权限和获取权限</p>
    </div>

    <!-- 权限状态 -->
    <div class="bg-white rounded-lg border border-gray-200 p-4">
      <h3 class="text-lg font-medium text-gray-900 mb-4">权限状态</h3>
      <div class="flex items-center justify-between mb-4">
        <span class="text-sm text-gray-700">当前状态:</span>
        <span 
          :class="[
            'text-sm font-medium',
            permissionStatus === 'granted' ? 'text-green-600' : 
            permissionStatus === 'denied' ? 'text-red-600' : 
            'text-orange-600'
          ]"
        >
          {{ 
            permissionStatus === 'granted' ? '✅ 已授权' : 
            permissionStatus === 'denied' ? '❌ 被拒绝' : 
            '⚠️ 未知' 
          }}
        </span>
      </div>

      <!-- 权限请求按钮 -->
      <button
        @click="requestMicrophonePermission"
        :disabled="permissionStatus === 'granted'"
        :class="[
          'w-full px-4 py-3 rounded-lg text-sm font-medium transition-colors',
          permissionStatus === 'granted' 
            ? 'bg-green-100 text-green-700 cursor-not-allowed' 
            : 'bg-blue-600 text-white hover:bg-blue-700'
        ]"
      >
        {{ 
          permissionStatus === 'granted' ? '✅ 麦克风权限已获取' : 
          '🎤 请求麦克风权限' 
        }}
      </button>
    </div>

    <!-- 测试结果 -->
    <div v-if="testResult" class="bg-white rounded-lg border border-gray-200 p-4">
      <h3 class="text-lg font-medium text-gray-900 mb-4">测试结果</h3>
      <div
        :class="[
          'p-4 rounded-lg border',
          testResult.status === 'success' ? 'bg-green-50 border-green-200' : 
          'bg-red-50 border-red-200'
        ]"
      >
        <div class="flex justify-between items-start">
          <div>
            <div class="font-medium" 
              :class="testResult.status === 'success' ? 'text-green-800' : 'text-red-800'">
              {{ testResult.title }}
            </div>
            <div class="text-sm mt-1 whitespace-pre-line" 
              :class="testResult.status === 'success' ? 'text-green-600' : 'text-red-600'">
              {{ testResult.message }}
            </div>
          </div>
          <div class="text-2xl">
            {{ testResult.status === 'success' ? '✅' : '❌' }}
          </div>
        </div>
      </div>
    </div>

    <!-- 返回按钮 -->
    <div class="text-center">
      <button
        @click="goBack"
        class="btn-secondary"
      >
        返回语音输入
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';

const permissionStatus = ref<'granted' | 'denied' | 'unknown' | ''>('');
const testResult = ref<{
  status: 'success' | 'error';
  title: string;
  message: string;
} | null>(null);

onMounted(async () => {
  // 检查麦克风权限状态
  await checkMicrophonePermission();
});

// 检查麦克风权限
const checkMicrophonePermission = async (): Promise<boolean> => {
  try {
    console.log('检查麦克风权限...');
    
    // 检查是否支持现代麦克风API
    if (!navigator.mediaDevices?.getUserMedia) {
      console.warn('浏览器不支持现代麦克风API');
      permissionStatus.value = 'unknown';
      return false;
    }
    
    // 尝试获取权限
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    stream.getTracks().forEach(track => track.stop()); // 立即停止录音
    console.log('麦克风权限已获取');
    permissionStatus.value = 'granted';
    return true;
  } catch (error) {
    console.warn('麦克风权限检查失败:', error);
    permissionStatus.value = 'denied';
    return false;
  }
};

// 请求麦克风权限
const requestMicrophonePermission = async () => {
  console.log('请求麦克风权限...');
  
  try {
    if (!navigator.mediaDevices?.getUserMedia) {
      throw new Error('浏览器不支持麦克风API');
    }
    
    console.log('使用现代API请求权限...');
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    
    if (stream) {
      stream.getTracks().forEach(track => track.stop()); // 立即停止
      permissionStatus.value = 'granted';
      
      // 获取设备信息
      const audioTracks = stream.getAudioTracks();
      const deviceInfo = audioTracks.length > 0 ? audioTracks[0].label : '未知设备';
      
      testResult.value = {
        status: 'success',
        title: '麦克风权限获取成功',
        message: `设备: ${deviceInfo}\n\n现在可以正常使用语音录音功能了。`
      };
      
      console.log('权限请求成功，设备:', deviceInfo);
    }
    
  } catch (error: any) {
    console.error('权限请求失败:', error);
    permissionStatus.value = 'denied';
    
    let errorMessage = '麦克风权限请求失败';
    
    if (error.name === 'NotAllowedError') {
      errorMessage = '麦克风权限被拒绝\n\n请尝试：\n1. 刷新页面后重试\n2. 在浏览器设置中允许麦克风权限\n3. 尝试使用Chrome浏览器';
    } else if (error.name === 'NotFoundError') {
      errorMessage = '未找到麦克风设备\n\n请检查：\n1. 设备是否有麦克风硬件\n2. 麦克风是否被其他应用占用';
    } else if (error.name === 'NotSupportedError') {
      errorMessage = '浏览器不支持音频录制\n\n建议：\n1. 使用Chrome浏览器\n2. 使用Safari浏览器';
    } else if (error.name === 'SecurityError') {
      errorMessage = '安全错误\n\n请在HTTPS环境下使用此功能，或使用localhost访问';
    } else if (error.message === '浏览器不支持麦克风API') {
      errorMessage = '浏览器不支持麦克风API\n\n建议：\n1. 使用Chrome浏览器\n2. 使用Safari浏览器\n3. 更新浏览器版本';
    }
    
    testResult.value = {
      status: 'error',
      title: '麦克风权限获取失败',
      message: errorMessage
    };
  }
};

const goBack = () => {
  // 触发父组件返回语音输入页面
  const event = new CustomEvent('voice-settings-back');
  window.dispatchEvent(event);
};
</script>

<style scoped>
.btn-secondary {
  @apply bg-gray-600 text-white font-medium py-3 px-4 rounded-lg hover:bg-gray-700 transition-colors;
}
</style> 